<template>
  <el-config-provider :locale="locale">
    <div class="main-layout">
      <!-- 页面头部 -->
      <el-card class="header-card">
        <div class="header-content">
          <div class="title-section">
            <h1 class="main-title">
              <el-icon class="title-icon"><Star /></el-icon>
              我的收藏
            </h1>
            <div class="subtitle">高效管理，精准收藏</div>
          </div>
          <div class="actions-section">
            <el-button type="primary" @click="showCreateFolderDialog" class="create-btn">
              <el-icon><Plus /></el-icon>新建收藏夹
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 收藏夹和题目列表区域 -->
      <div class="content-section">
        <!-- 收藏夹列表 -->
        <el-card class="folders-card">
          <template #header>
            <div class="card-header">
              <el-icon class="header-icon"><Folder /></el-icon>
              <span class="header-title">收藏夹</span>
            </div>
          </template>
          
          <div class="folders-list">
            <div
              class="folder-item"
              :class="{ active: activeFolder === 'all' }"
              @click="handleFolderSelect('all')"
            >
              <el-icon><Star /></el-icon>
              <span>全部收藏</span>
            </div>
            <div
              v-for="folder in folders"
              :key="folder.id"
              class="folder-item"
              :class="{ active: activeFolder === folder.id }"
              @click="handleFolderSelect(folder.id)"
            >
              <el-icon><Folder /></el-icon>
              <span>{{ folder.name }}</span>
              <div class="folder-actions">
                <el-button
                  type="text"
                  size="small"
                  @click.stop="showEditFolderDialog(folder)"
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click.stop="confirmDeleteFolder(folder)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 题目列表 -->
        <el-card class="questions-card">
          <template #header>
            <div class="card-header">
              <el-icon class="header-icon"><List /></el-icon>
              <span class="header-title">题目列表</span>
              <div class="header-extra">
                <el-tag type="success" size="small">总数: {{ total }}</el-tag>
              </div>
            </div>
          </template>

          <div class="questions-header">
            <div class="search-box">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索题目"
                clearable
                @clear="handleSearch"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            <div class="filter-box">
              <el-select v-model="filters.questionType" placeholder="题目类型" clearable>
                <el-option label="单选题" value="1" />
                <el-option label="多选题" value="2" />
                <el-option label="填空题" value="3" />
                <el-option label="主观题" value="4" />
              </el-select>
              <el-select v-model="filters.examType" placeholder="考试类型" clearable>
                <el-option
                  v-for="type in examTypes"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
              <el-select v-model="filters.subjectId" placeholder="科目" clearable>
                <el-option
                  v-for="subject in subjects"
                  :key="subject.subjectId"
                  :label="subject.name"
                  :value="subject.subjectId"
                />
              </el-select>
              <div class="filter-actions">
                <el-button type="primary" @click="handleSearch" class="filter-btn">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
              </div>
            </div>
          </div>

          <div class="questions-list" v-loading="loading">
            <el-table 
              :data="favoriteQuestions" 
              style="width: 100%"
              :row-class-name="tableRowClassName"
              border
            >
              <el-table-column prop="questionId" label="题号" width="60" />
              <el-table-column prop="subjectName" label="科目" width="90">
                <template #default="{ row }">
                  <div>{{ row.subjectId ? subjects.find(s => s.subjectId == row.subjectId)?.name : '未知' }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="content" label="题目内容" class-name="content-cell" min-width="250">
                <template #default="{ row }">
                  <div v-html="formatQuestionContent(row.content)"></div>
                </template>
              </el-table-column>
              <el-table-column prop="typeId" label="考试类型" width="80">
                <template #default="{ row }">
                  <div>数{{ row.typeId }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="questionType" label="题目类型" width="80">
                <template #default="{ row }">
                  <el-tag :type="getQuestionTypeTag(row.questionType)" size="small">
                    {{ getQuestionTypeLabel(row.questionType) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="year" label="年份" width="60" />
              <el-table-column label="操作" width="140" fixed="right">
                <template #default="{ row }">
                  <div class="action-buttons">
                    <el-button
                      type="primary"
                      link
                      @click="viewQuestionDetail(row)"
                      class="action-btn view-btn"
                    >
                      <el-icon><View /></el-icon>
                      查看
                    </el-button>
                    <el-button
                      type="primary"
                      link
                      @click="showMoveQuestionDialog(row)"
                      class="action-btn move-btn"
                    >
                      <el-icon><Position /></el-icon>
                      移动
                    </el-button>
                    <el-button
                      type="danger"
                      link
                      @click="confirmRemoveFavorite(row)"
                      class="action-btn remove-btn"
                    >
                      <el-icon><Delete /></el-icon>
                      取消
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-card>
      </div>

      <!-- 题目详情弹窗 -->
      <el-dialog
        :model-value="activeDialog === 'questionDetail'"
        @close="activeDialog = ''"
        title="题目详情"
        width="70%"
        class="question-dialog"
      >
        <div v-if="currentQuestion" class="question-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="科目">
              <el-tag size="small" effect="plain">{{ currentQuestion.subjectName || '未知' }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="题型">
              <el-tag size="small" :type="getQuestionTypeTag(currentQuestion.questionType)">
                {{ getQuestionTypeLabel(currentQuestion.questionType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="序号">
              <el-tag type="primary" effect="dark">
                {{ currentQuestion.originalSequence || '未设置' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="年份">{{ currentQuestion.year || '未知' }}</el-descriptions-item>
          </el-descriptions>

          <div class="detail-section">
            <h3>题目内容</h3>
            <div class="question-content" v-html="formatQuestionContent(currentQuestion.content)"></div>
          </div>

          <div v-if="currentQuestion.questionType === 'single_choice'" class="detail-section">
            <h3>选项</h3>
            <div class="options-grid">
              <div v-for="(option, index) in currentQuestion.options" :key="index" class="option-item">
                <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
                <span class="option-content" v-html="formatQuestionContent(option)"></span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h3>答案</h3>
            <div class="answer-content">
              <template v-if="currentQuestion.questionType === 'single_choice'">
                <el-tag type="success" effect="dark">{{ formatChoiceAnswer(currentQuestion.answer) }}</el-tag>
              </template>
              <template v-else-if="currentQuestion.questionType === 'fill_in_the_blank'">
                <div v-html="formatQuestionContent(currentQuestion.answer)"></div>
              </template>
              <template v-else-if="currentQuestion.questionType === 'subjective'">
                <div v-html="formatQuestionContent(currentQuestion.answer)"></div>
              </template>
              <template v-else>
                <span>未知题型</span>
              </template>
            </div>
          </div>

          <div v-if="currentQuestion.analysis" class="detail-section">
            <h3>解析</h3>
            <div class="analysis-content" v-html="formatQuestionContent(currentQuestion.analysis)"></div>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="activeDialog = ''">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 移动到收藏夹对话框 -->
      <el-dialog
        v-model="moveToFolderDialogVisible"
        title="移动到收藏夹"
        width="30%"
        class="move-dialog"
      >
        <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
          <el-form-item label="收藏夹" prop="folderId">
            <el-select v-model="selectedFolderId" placeholder="请选择收藏夹" style="width: 100%">
              <el-option
                v-for="folder in folders"
                :key="folder.id"
                :label="folder.name"
                :value="folder.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="moveToFolderDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="moveQuestion">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 新建收藏夹对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="新建收藏夹"
        width="30%"
      >
        <el-form>
          <el-form-item label="收藏夹名称" required>
            <el-input v-model="folderName" placeholder="请输入收藏夹名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="createFolder">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 编辑收藏夹对话框 -->
      <el-dialog
        v-model="editDialogVisible"
        title="编辑收藏夹"
        width="30%"
      >
        <el-form>
          <el-form-item label="收藏夹名称" required>
            <el-input v-model="editFolderName" placeholder="请输入收藏夹名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="editFolder">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Star, Folder, Search, View, Position, TrendCharts, List } from '@element-plus/icons-vue'
import axios from 'axios'
import { useUserStore } from '@/store/user'
import zhCn from 'element-plus/es/locale/lang/zh-cn'

// 导入KaTeX
import 'katex/dist/katex.min.css';
import katex from 'katex';

// 定义locale变量
const locale = ref(zhCn)

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const loading = ref(false)
const favoriteQuestions = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const dialogVisible = ref(false)
const currentQuestion = ref(null)
const activeFolder = ref('all')
const moveToFolderDialogVisible = ref(false)
const selectedFolderId = ref(null)
const folders = ref([])
const currentQuestionToMove = ref(null)
const formRef = ref(null)
const activeDialog = ref('') // '', 'questionDetail', 'createFolder'
const searchKeyword = ref('')
const subjects = ref([
  { subjectId: '1', name: '高等数学' },
  { subjectId: '2', name: '线性代数' },
  { subjectId: '3', name: '概率论与数理统计' }
])
const examTypes = ref([]) // 添加考试类型数据
const folderName = ref('')
const editDialogVisible = ref(false)
const editFolderName = ref('')
const currentEditFolder = ref(null)

// 添加筛选条件
const filters = ref({
  questionType: '',
  examType: '',
  subjectId: ''
})

const form = ref({
  name: '',
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入收藏夹名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

// ====================== LaTeX渲染相关 ======================
/* 格式化题目内容 - 使用KaTeX处理数学公式 */
const formatQuestionContent = (content) => {
  if (!content) return '';
  
  try {
    let processedContent = content
      .replace(/\\n/g, '\n')  // 处理换行符
      .replace(/\\\$/g, '###DOLLAR###')  // 临时替换转义的美元符号
      .replace(/\$\$([^$]+)\$\$/g, (match, formula) => {
        // 处理块级数学公式 $$...$$
        try {
          return katex.renderToString(formula.trim(), {
            displayMode: true,
            throwOnError: false,
            strict: false,
            trust: true
          });
        } catch (error) {
          console.warn('KaTeX block formula error:', error, 'Formula:', formula);
          return `<span class="katex-error">$$${formula}$$</span>`;
        }
      })
      .replace(/\$([^$\n]+)\$/g, (match, formula) => {
        // 处理行内数学公式 $...$
        try {
          return katex.renderToString(formula.trim(), {
            displayMode: false,
            throwOnError: false,
            strict: false,
            trust: true
          });
        } catch (error) {
          console.warn('KaTeX inline formula error:', error, 'Formula:', formula);
          return `<span class="katex-error">$${formula}$</span>`;
        }
      })
      .replace(/###DOLLAR###/g, '$')  // 恢复转义的美元符号
      .replace(/\n/g, '<br>');  // 简单的换行处理
    
    return processedContent;
  } catch (error) {
    console.error('formatQuestionContent error:', error);
    return content.replace(/\\n/g, '<br>');
  }
};

// 格式化选择题答案
const formatChoiceAnswer = (answer) => {
  if (!answer) return '未知'
  
  // 如果答案已经是字母格式（如 'A', 'B'），直接返回
  if (typeof answer === 'string' && answer.match(/^[A-Z]$/)) {
    return answer
  }
  
  // 如果答案是数字索引格式（如 0, 1, 2, 3），转换为字母
  if (typeof answer === 'number' || (typeof answer === 'string' && answer.match(/^\d+$/))) {
    const index = parseInt(answer)
    return String.fromCharCode(65 + index)
  }
  
  // 其他情况直接返回
  return answer.toString()
}

// 检查登录状态
const checkLoginStatus = () => {
  // 首先尝试从 sessionStorage 获取
  const sessionUserId = sessionStorage.getItem('userId')
  // 然后从 store 获取
  const storeUserId = userStore.userId
  
  console.log('Session userId:', sessionUserId)
  console.log('Store userId:', storeUserId)
  
  // 如果两个地方都没有，说明未登录
  if (!sessionUserId && !storeUserId) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return false
  }
  
  // 优先使用 store 中的 ID
  return storeUserId || sessionUserId
}

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    if (newPath === '/user/home') {
      router.replace('/home')
    }
  },
  { immediate: true }
)

const getQuestionTypeLabel = (type) => {
  console.log('Question type:', type) // Debug log
  const types = {
    'single_choice': '选择题',
    'multiple_choice': '多选题',
    'fill_in_the_blank': '填空题',
    'subjective': '主观题'
  }
  const label = types[type] || '未知'
  console.log('Question type label:', label) // Debug log
  return label
}

// 获取考试类型数据
const fetchExamTypes = async () => {
  try {
    const response = await axios.get('/api/favorites/difficulty-levels')
    if (response.status === 200) {
      examTypes.value = response.data.map(item => ({
        value: item.value,
        label: item.label || `数${item.value}`
      }))
    }
  } catch (error) {
    console.error('获取考试类型失败:', error)
    ElMessage.error('获取考试类型失败')
  }
}

// 刷新数据
const refreshData = async (folderId = null) => {
  try {
    // 刷新收藏夹列表
    await fetchFolders()
    // 刷新题目列表
    await fetchFavoriteQuestions(folderId)
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  }
}

// 修改 fetchFavoriteQuestions 函数
const fetchFavoriteQuestions = async (folderId = null) => {
  try {
    loading.value = true
    const userId = checkLoginStatus()
    if (!userId) return

    const params = {
      userId,
      page: currentPage.value,
      pageSize: pageSize.value,
      examType: filters.value.examType,
      questionType: filters.value.questionType,
      subjectId: filters.value.subjectId
    }

    let response
    if (folderId) {
      // 使用新的URL格式获取收藏夹中的题目
      response = await axios.get(`/api/favorites/folders/${folderId}/questions`, { params })
    } else {
      // 获取所有收藏的题目
      response = await axios.get('/api/favorites/questions', { params })
    }

    console.log('收藏题目列表原始响应:', response) // 添加完整响应日志
    console.log('收藏题目列表数据结构:', {
      status: response.status,
      data: response.data,
      list: response.data?.list,
      firstItem: response.data?.list?.[0]
    }) // 添加数据结构日志

    if (response.status === 200 && response.data) {
      favoriteQuestions.value = response.data.list.map(question => {
        console.log('处理前的题目数据:', question) // 添加单个题目数据日志
        const processedQuestion = {
          ...question,
          // 确保favoriteId存在
          favoriteId: question.favoriteId || question.id,
          options: Array.isArray(question.options) ? question.options : []
        }
        console.log('处理后的题目数据:', processedQuestion) // 添加处理后的数据日志
        return processedQuestion
      })
      total.value = response.data.total
    } else {
      favoriteQuestions.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取收藏题目失败:', error)
    ElMessage.error('获取收藏题目失败')
    favoriteQuestions.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 修改 fetchFolders 函数
const fetchFolders = async () => {
  const userId = checkLoginStatus()
  if (!userId) return

  try {
    const response = await axios.get('/api/favorites/folders', {
      params: {
        userId
      }
    })
    
    if (response.status === 200 && Array.isArray(response.data)) {
      folders.value = response.data.map(folder => ({
        id: folder.id,
        name: folder.name,
        description: folder.description || '',
        count: folder.count || 0
      }))
    } else {
      folders.value = []
    }
  } catch (error) {
    console.error('获取收藏夹列表失败:', error)
    ElMessage.error('获取收藏夹列表失败')
    folders.value = []
  }
}

// 显示创建对话框
const showCreateFolderDialog = () => {
  folderName.value = ''
  dialogVisible.value = true
}

// 创建收藏夹
const createFolder = async () => {
  if (!folderName.value.trim()) {
    ElMessage.warning('请输入收藏夹名称')
    return
  }

  try {
    const userId = checkLoginStatus()
    if (!userId) return

    const response = await axios.post('/api/favorites/folders', {
      userId,
      name: folderName.value.trim()
    })

    if (response.status === 200) {
      ElMessage.success('创建成功')
      dialogVisible.value = false
      folderName.value = ''
      // 刷新数据
      await refreshData(activeFolder.value === 'all' ? null : Number(activeFolder.value))
    } else {
      ElMessage.error('创建失败')
    }
  } catch (error) {
    if (error.response?.status === 401) {
      userStore.clearUser()
      ElMessage.error('登录已过期，请重新登录')
    } else {
      console.error('创建收藏夹失败:', error)
      ElMessage.error('创建收藏夹失败')
    }
  }
}

// 处理收藏夹选择
const handleFolderSelect = async (index) => {
  activeFolder.value = index
  currentPage.value = 1
  await refreshData(index === 'all' ? null : Number(index))
}

// 查看题目详情
const viewQuestionDetail = async (question) => {
  try {
    loading.value = true
    const response = await axios.get(`/api/questions/${question.questionId}`)
    if (response.status === 200 && response.data) {
      const questionDetail = response.data
      
      console.log('题目详情原始数据:', questionDetail) // 调试日志
      
      // 处理选项数据
      let options = []
      if (questionDetail.questionType === 'single_choice' || questionDetail.questionType === 'multiple_choice') {
        try {
          if (typeof questionDetail.options === 'string') {
            options = JSON.parse(questionDetail.options)
          } else if (Array.isArray(questionDetail.options)) {
            options = questionDetail.options
          }
        } catch (e) {
          console.error('解析选项失败:', e)
          options = []
        }
      }

      // 处理答案和解析
      let answer = ''
      let analysis = ''
      switch (questionDetail.questionType) {
        case 'single_choice':
        case 'multiple_choice':
          answer = questionDetail.choiceAnswer
          analysis = questionDetail.choiceAnalysis
          break
        case 'fill_in_the_blank':
          answer = questionDetail.answerTemplate
          analysis = questionDetail.fillblankAnalysis
          break
        case 'subjective':
          answer = questionDetail.referenceAnswer
          analysis = questionDetail.subjectiveAnalysis
          break
      }

      // 获取科目名称 - 修复科目显示问题
      console.log('科目ID:', questionDetail.subjectId, '类型:', typeof questionDetail.subjectId)
      console.log('可用科目:', subjects.value)
      
      const subject = subjects.value.find(s => 
        s.subjectId == questionDetail.subjectId || 
        s.subjectId === questionDetail.subjectId.toString() ||
        s.subjectId === parseInt(questionDetail.subjectId)
      )
      const subjectName = subject ? subject.name : `科目${questionDetail.subjectId}`

      console.log('匹配到的科目:', subject, '科目名称:', subjectName)

      currentQuestion.value = {
        ...questionDetail,
        subjectName,
        options,
        answer,
        analysis,
        // 确保序号正确显示
        originalSequence: questionDetail.originalSequence || questionDetail.original_sequence,
        // 确保年份正确显示
        year: questionDetail.year,
        favoriteId: questionDetail.favoriteId
      }
      
      console.log('处理后的题目数据:', currentQuestion.value) // 调试日志
      activeDialog.value = 'questionDetail'
    }
  } catch (error) {
    console.error('获取题目详情失败:', error)
    ElMessage.error('获取题目详情失败')
  } finally {
    loading.value = false
  }
}

// 确认取消收藏
const confirmRemoveFavorite = (question) => {
  ElMessageBox.confirm(
    '确定要取消收藏这道题目吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    removeFavorite(question)
  }).catch(() => {
    // 用户取消操作
  })
}

// 取消收藏
const removeFavorite = async (question) => {
  const userId = checkLoginStatus()
  if (!userId) return

  try {
    await axios.delete(`/api/favorites/questions/${question.questionId}`, {
      data: { userId } // 将 userId 放在请求体中
    })
    ElMessage.success('取消收藏成功')
    fetchFavoriteQuestions(activeFolder.value === 'all' ? null : Number(activeFolder.value))
  } catch (error) {
    console.error('Error removing favorite:', error)
    if (error.response?.status === 401) {
      userStore.clearUser()
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('取消收藏失败')
    }
  }
}

const handleSearch = () => {
  if (!checkLoginStatus()) return
  currentPage.value = 1
  refreshData(activeFolder.value === 'all' ? null : Number(activeFolder.value))
}

const handleSizeChange = (val) => {
  if (!checkLoginStatus()) return
  pageSize.value = val
  currentPage.value = 1
  refreshData(activeFolder.value === 'all' ? null : Number(activeFolder.value))
}

const handleCurrentChange = (val) => {
  if (!checkLoginStatus()) return
  currentPage.value = val
  refreshData(activeFolder.value === 'all' ? null : Number(activeFolder.value))
}

// 添加题型标签样式
const getQuestionTypeTag = (type) => {
  const types = {
    'single_choice': 'primary',
    'multiple_choice': 'success',
    'fill_in_the_blank': 'warning',
    'subjective': 'info'
  }
  return types[type] || 'info'
}

// 添加表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return 'even-row'
  }
  return 'odd-row'
}

// 显示移动到收藏夹对话框
const showMoveQuestionDialog = async (question) => {
  try {
    loading.value = true
    const response = await axios.get(`/api/questions/${question.questionId}`)
    if (response.status === 200 && response.data) {
      const questionDetail = response.data
      if (!questionDetail.favoriteId) {
        ElMessage.error('无法获取收藏信息')
        return
      }
      currentQuestionToMove.value = {
        ...question,
        favoriteId: questionDetail.favoriteId
      }
      moveToFolderDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取题目信息失败:', error)
    ElMessage.error('获取题目信息失败')
  } finally {
    loading.value = false
  }
}

// 移动到收藏夹
const moveToFolder = async () => {
  if (!selectedFolderId.value || !currentQuestionToMove.value) {
    ElMessage.warning('请选择目标收藏夹')
    return
  }

  try {
    const userId = checkLoginStatus()
    if (!userId) return

    const response = await axios.post(
      `/api/favorites/folders/${selectedFolderId.value}/questions/${currentQuestionToMove.value.questionId}`,
      { userId }
    )

    if (response.status === 200) {
      ElMessage.success('移动成功')
      moveToFolderDialogVisible.value = false
      selectedFolderId.value = null
      currentQuestionToMove.value = null
      // 刷新数据
      await refreshData(activeFolder.value === 'all' ? null : Number(activeFolder.value))
    } else {
      ElMessage.error('移动失败')
    }
  } catch (error) {
    console.error('移动题目失败:', error)
    ElMessage.error('移动题目失败')
  }
}

// 显示编辑对话框
const showEditFolderDialog = (folder) => {
  currentEditFolder.value = folder
  editFolderName.value = folder.name
  editDialogVisible.value = true
}

// 编辑收藏夹
const editFolder = async () => {
  if (!editFolderName.value.trim()) {
    ElMessage.warning('请输入收藏夹名称')
    return
  }

  // 检查是否与其他收藏夹重名
  const isDuplicate = folders.value.some(
    folder => folder.id !== currentEditFolder.value.id && 
    folder.name === editFolderName.value.trim()
  )

  if (isDuplicate) {
    ElMessage.warning('收藏夹名称已存在')
    return
  }

  try {
    const userId = checkLoginStatus()
    if (!userId) return

    const response = await axios.put(`/api/favorites/folders/${currentEditFolder.value.id}`, {
      name: editFolderName.value.trim()
    })

    if (response.status === 200) {
      ElMessage.success('修改成功')
      editDialogVisible.value = false
      editFolderName.value = ''
      const currentFolderId = currentEditFolder.value.id
      currentEditFolder.value = null
      // 刷新数据
      await refreshData(activeFolder.value === 'all' ? null : Number(activeFolder.value))
    } else {
      ElMessage.error('修改失败')
    }
  } catch (error) {
    console.error('修改收藏夹失败:', error)
    ElMessage.error('修改收藏夹失败')
  }
}

onMounted(() => {
  // 初始化用户状态
  userStore.initialize()
  if (checkLoginStatus()) {
    fetchFavoriteQuestions()
    fetchFolders()
    fetchExamTypes() // 添加获取考试类型
  }
})
</script>

<style scoped>
/* 主布局 */
.main-layout {
  padding: 20px;
  min-height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
  background: 
    radial-gradient(circle at 20% 80%, rgba(64, 158, 255, 0.05) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(103, 194, 58, 0.05) 0%, transparent 50%),
    linear-gradient(135deg, #f5f7fa 0%, #f8fafe 100%);
  position: relative;
}

.main-layout::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 25% 25%, rgba(64, 158, 255, 0.02) 0%, transparent 50%),
    radial-gradient(circle at 75% 75%, rgba(103, 194, 58, 0.02) 0%, transparent 50%);
  pointer-events: none;
  z-index: -1;
}

/* 卡片通用样式 */
.header-card,
.folders-card,
.questions-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05), 0 2px 4px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
  margin-bottom: 20px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.header-card::before,
.folders-card::before,
.questions-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #409eff, #66b1ff, #409eff);
  background-size: 200% 100%;
  animation: shimmer 3s ease-in-out infinite;
}

.header-card:hover,
.folders-card:hover,
.questions-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.15), 0 4px 8px rgba(0, 0, 0, 0.1);
}

@keyframes shimmer {
  0% { background-position: -200% 0; }
  100% { background-position: 200% 0; }
}

/* 页面头部 */
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.title-section .main-title {
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  color: #409eff;
  font-size: 24px;
  filter: drop-shadow(0 2px 4px rgba(64, 158, 255, 0.3));
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.create-btn {
  background: #409eff;
  border-color: #409eff;
  padding: 8px 20px;
  transition: all 0.3s ease;
}

.create-btn:hover {
  background: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
}

/* 内容区域 */
.content-section {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

/* 收藏夹列表 */
.folders-card {
  width: 200px;
  flex-shrink: 0;
}

.folders-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: calc(100vh - 300px);
  overflow-y: auto;
}

.folder-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8f9fa;
  border: 1px solid transparent;
  font-size: 13px;
}

.folder-item:hover {
  background: #f0f9ff;
  border-color: #e1f3ff;
  transform: translateX(4px);
}

.folder-item.active {
  background: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}

.folder-actions {
  margin-left: auto;
  display: none;
  gap: 4px;
}

.folder-item:hover .folder-actions {
  display: flex;
}

/* 题目列表 */
.questions-card {
  flex: 1;
  min-width: 0;
}

.questions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px;
  flex-wrap: wrap;
}

.search-box {
  width: 300px;
}

.filter-box {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-box .el-select {
  width: 140px;
}

.filter-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.filter-btn {
  margin-left: 8px;
}

.filter-btn .el-button {
  padding: 8px 16px;
}

.filter-btn .el-icon {
  margin-right: 4px;
}

.questions-list {
  margin-top: 20px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 2px;
  justify-content: center;
  min-width: 140px;
}

.action-btn {
  font-size: 12px;
  padding: 2px 4px;
  border-radius: 3px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  white-space: nowrap;
}

.action-btn .el-icon {
  margin-right: 2px;
}

.view-btn:hover {
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
}

.move-btn:hover {
  color: #67c23a;
  background: rgba(103, 194, 58, 0.1);
}

.remove-btn:hover {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
}

/* 题目内容样式 */
:deep(.el-table .cell) {
  white-space: normal;
  word-break: break-word;
  line-height: 1.4;
}

:deep(.el-table__row) {
  height: auto;
}

:deep(.el-table__cell) {
  padding: 6px 0;
}

:deep(.el-table .content-cell) {
  min-width: 250px;
  max-width: 400px;
}

:deep(.el-table .content-cell .cell) {
  padding: 6px 8px;
}

/* 调整表格列宽 */
:deep(.el-table) {
  font-size: 13px;
}

:deep(.el-table .el-table__header th) {
  padding: 8px 0;
  font-weight: 500;
}

:deep(.el-table .el-table__body td) {
  padding: 6px 0;
}

/* 分页 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-layout {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .content-section {
    flex-direction: column;
  }
  
  .folders-card {
    width: 100%;
  }
  
  .questions-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    width: 100%;
  }
  
  .filter-box {
    flex-wrap: wrap;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 6px;
  }
}

@media (max-width: 480px) {
  .dialog-footer {
    flex-direction: column;
    gap: 10px;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}
</style>